import { login, logout, register, getUserInfo, modifyInfo } from '@/api/login'
import { setToken, getToken, removeToken } from '@/api/token'
import { Message } from 'element-ui'
import { constantRoutes, asyncRoutes, anyRoutes } from '@/router'
import router from '@/router'

const state = {
  userInfo: {},
  routers: [],
  token: getToken(),
  resultAsyncRouters: [],
  resultAllRouters: [],
  menu: [
    {
      name: "punch",
      path: '/punch',
      label: "健康打卡",
      icon: "place",
    },
    {
      name: "punchrecord",
      path: '/punchrecord',
      label: "打卡记录",
      icon: "sunny",
    },
    {
      name: "account",
      path: '/account',
      label: '用户管理',
      icon: "user"
    },
    {
      name: "statistic",
      path: '/statistic',
      label: "统计",
      icon: "s-data",
    }
  ],
  lastMenu: []
}

const mutations = {
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  GETROUTERS(state, routers) {
    state.routers = routers;
  },
  GETTOKEN(state, token) {
    state.token = token
  },
  //计算机算出的异步路由
  SET_RESULTASYNCROUTERS(state, asyncRoutes) {
    state.resultAsyncRouters = asyncRoutes
    state.resultAllRouters = constantRoutes
    state.resultAllRouters.forEach(item => {
      if (item.children) {
        item.children = asyncRoutes
      }
    });
    state.resultAllRouters = state.resultAllRouters.concat(anyRoutes)
    router.addRoutes(state.resultAllRouters)
  },
  GETMENU(state, menuInfo) {
    state.menu.forEach(item => {
      if (menuInfo.indexOf(item.name) !== -1) {
        state.lastMenu.push(item)
      }
    });
  },
  CLEAR(state) {
    state.userInfo = {}
    state.token = '',
    state.routers = '',
    state.resultAsyncRouters = {},
    state.resultAllRouters = [],
    state.lastMenu = []
    removeToken()
  }
}

const computedAsyncRouters = (asyncRoutes, routers) => {
  return asyncRoutes.filter(item => {
    if (routers.indexOf(item.name) !== -1) {
      if (item.children) {
        computedAsyncRouters(item.children, routers)
      }
      return true;
    }
  })
}

const actions = {
  login({ commit }, user) {
    return new Promise((resolve, reject) => {
      login(user.username, user.password).then(data => {
        if (data.success) {
          Message({
            type: 'success',
            message: '欢迎主人回家！',
            showClose: true
          })
          commit('GETTOKEN', data.data)
          setToken(data.data)
          resolve()
        } else {
          reject(data.message)
        }
      }).catch(error => {
        console.log(error)
      })
    })
  },
  // 退出
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout().then(data => {
        if (data.success) {
          commit('CLEAR')
          resolve()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  register({ commit }, user) {
    return new Promise((resolve, reject) => {
      register(user.username, user.password).then(data => {
        if (data.success) {
          Message({
            type: 'success',
            message: '恭喜你，注册成功，赶快去登录吧！！！',
            showClose: true
          })
          resolve()
        } else {
          Message({
            type: 'error',
            message: data.message,
            showClose: true
          })
          reject()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  getUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(data => {
        if (data.success) {
          commit('GETUSERINFO', data.data.user),
          commit('GETROUTERS', data.data.routers),
          commit('SET_RESULTASYNCROUTERS', computedAsyncRouters(asyncRoutes, data.data.routers)),
          commit('GETMENU', data.data.routers)
          resolve();
        } else {
          reject()
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  modifyInfo({ commit }, form) {
    return new Promise((resolve, reject) => {
      modifyInfo(form).then(data => {
        if (data.success) {
          Message({
            type: 'success',
            message: '密码修改成功赶快去登录吧！',
            showClose: true
          })
          resolve()
        } else {
          reject()
        }
      })
    })
  }
}


export default {
  state,
  mutations,
  actions
}


